<!DOCTYPE html>
<html>

<head>
  <!-- 页面meta -->
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>管理后台</title>
  <meta name="description" content="管理后台">
  <meta name="keywords" content="管理后台">
  <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../plugins/elementui/index.css">
  <script src="../js/vue.js"></script>
  <script src="../plugins/elementui/index.js"></script>
  <script src="../js/axios-0.18.0.js"></script>
  <style>
    /* title */
    .content-header {
      position: relative;
      padding: 15px 15px 0 15px;
      /* margin-top: 70px; */
    }

    .content-header>h1 {
      margin: 0;
      font-size: 24px;
      font-weight: normal;
    }

    .content-header>h1>small {
      font-size: 15px;
      display: inline-block;
      padding-left: 4px;
      font-weight: 300;
    }

    .content-header>.breadcrumb {
      float: right;
      background: transparent;
      margin-top: 0;
      margin-bottom: 0;
      font-size: 12px;
      padding: 7px 5px;
      position: absolute;
      top: 20px;
      right: 10px;
      border-radius: 2px;
    }

    .app-container {
      background: #fff;
      margin: 15px 30px 15px 15px;
    }

    .box {
      position: relative;
      border-radius: 3px;
      background: #ffffff;
      border-top: 3px solid #3c8dbc;
      padding: 10px;
      margin-bottom: 20px;
      width: 100%;
      box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    }

    .filter-container {
      padding: 10px 0 15px 0;
    }

    .filter-container .el-button,
    .filter-container .el-input__inner {
      padding: 0 15px;
      height: 34px;
      line-height: 34px;
    }

    .el-dialog__body {
      padding: 20px;
    }

    .el-table .el-tag {
      margin: 0;
    }

    .pagination-container {
      text-align: center;
      margin-top: 20px;
    }
  </style>
</head>

<body class="hold-transition">
  <div id="app">

    <div class="content-header">
      <h1>网站管理<small>权限管理</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>网站站管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="app-container">
      <div class="box">

        <div class="filter-container">
          <el-input placeholder="账户名称" v-model="pagination.queryString" style="width: 200px;"
            class="filter-item"></el-input>
          <el-button @click="findSearchPage()" class="dalfBut">查询</el-button>
        </div>

        <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
          <el-table-column align="center" label="序号" type="index"></el-table-column>
          <el-table-column label="账号" align="center" prop="account">
          </el-table-column>
          <el-table-column label="会员等级" align="center" prop="userRole">
            <template slot-scope="scope">
              <span>{{ getRoleName(scope.row.userRole)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="注册时间" align="center" prop="created_at">
            <template slot-scope="scope">
              <span>{{ scope.row.createdAt }}</span>
            </template>
          </el-table-column>
          <el-table-column label="会员到期时间" align="center" prop="account_expiration_date">
            <template slot-scope="scope">
              <span>{{ scope.row.accountExpirationDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账号状态" align="center" prop="status">
            <template slot-scope="scope">
              <span>{{ getStatusText(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="380" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button size="mini" @click="toggleStatus(scope.row)">{{ scope.row.status === 1 ? '冻结' : '解封'
                }}</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="danger" @click="handleReset(scope.row)">重置密码</el-button>
              <el-button size="mini" type="info" @click="showRentalHistory(scope.row)">租号记录</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination class="pagiantion" @current-change="handleCurrentChange" :current-page="pagination.currentPage"
            :page-size="pagination.pageSize" layout="total, prev, pager, next, jumper" :total="pagination.total">
          </el-pagination>
        </div>

        <!-- 新增标签弹层 -->
        <div class="add-form">
          <el-dialog title="新增" :visible.sync="dialogFormVisible">
            <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
              <el-row>
                <el-col>
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="路径" prop="path">
                    <el-input v-model="formData.path" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="描述" prop="description">
                    <el-input v-model="formData.description" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleAdd()">确定</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 编辑标签弹层 -->
        <div class="add-form">
          <el-dialog title="编辑" :visible.sync="dialogFormVisibleEdit">
            <el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
              <el-row>
                <el-col>
                  <el-form-item label="账户过期时间" prop="accountExpirationDate">
                    <el-date-picker v-model="formData.accountExpirationDate" type="datetime" placeholder="选择日期和时间"
                      format="yyyy-MM-ddTHH:mm:ss" value-format="yyyy-MM-ddTHH:mm:ss" />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- 新增用户等级选择 -->
              <el-row>
                <el-col>
                  <el-form-item label="用户等级" prop="userRole">
                    <el-select v-model="formData.userRole" placeholder="请选择用户等级">
                      <el-option label="管理员" value="1"></el-option>
                      <el-option label="用户" value="2"></el-option>
                      <el-option label="普通会员" value="3"></el-option>
                      <el-option label="高级会员" value="4"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisibleEdit = false">取消</el-button>
              <el-button type="primary" @click="handleEdit()">确定</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 添加租号记录对话框 -->
        <div class="add-form">
          <el-dialog title="租号记录" :visible.sync="rentalHistoryVisible" width="70%">
            <el-table :data="rentalHistory" v-loading="historyLoading">
              <el-table-column prop="startTime" label="开始时间" width="180">
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.startTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="endTime" label="结束时间" width="180">
                <template slot-scope="scope">
                  {{ formatDateTime(scope.row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="游戏名称"></el-table-column>
              <el-table-column prop="gameId" label="账号ID"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                    {{ scope.row.status === 1 ? '租用中' : '已结束' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination @current-change="handleHistoryPageChange" :current-page="historyQuery.currentPage"
                :page-size="historyQuery.pageSize" layout="total, prev, pager, next, jumper" :total="historyTotal">
              </el-pagination>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</body>

<script>
  var vue = new Vue({
    el: '#app',
    data: {
      statusMap: {
        0: '冻结',
        1: '正常',
      },
      pagination: {//分页相关模型数据
        currentPage: 1,//当前页码
        pageSize: 10,//每页显示的记录数
        total: 0,//总记录数
        queryString: null//查询条件
      },
      dataList: [],//当前页要展示的分页列表数据
      subjectList: [],
      tableData: {},
      fbChoiceList: [{
        content: "",
      }],
      formData: {},//表单数据
      dialogFormVisible: false,//增加表单是否可见
      dialogFormVisibleEdit: false,
      rules: {//校验规则

      },
      rentalHistoryVisible: false,
      historyLoading: false,
      rentalHistory: [],
      historyTotal: 0,
      historyQuery: {
        currentPage: 1,
        pageSize: 10,
        userId: null
      },
      currentUser: null
    },
    //钩子函数，VUE对象初始化完成后自动执行
    created() {
      this.findPage();
    },
    methods: {
      validateConfirmPassword(rule, value, callback) {
        if (value === '') {
          callback(new Error('请输入确认密码'));
        } else if (value !== this.formData.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      getStatusText(status) {
        return this.statusMap[status] || '未知状态';
      },
      toggleStatus(row) {
        const newStatus = row.status === 1 ? 0 : 1;
        axios.put(`/users/${row.id}/status`, { status: newStatus }).then((res) => {
          if (res.data) {
            this.$message({
              message: `用户已${newStatus === 1 ? '解封' : '冻结'}`,
              type: 'success'
            });
            this.findPage();
          }
        }).catch((error) => {
          if (error == "Error: Request failed with status code 403") {
            this.$message.error("无操作权限");
          }
          if (error == "Error: Request failed with status code 400") {
            this.$message.error("系统管理员不能被禁用");
          }
        });
      },
      //编辑
      handleEdit() {
        axios.put("/users/" + this.formData.id, this.formData).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '恭喜你，编辑成功',
              type: 'success'
            });
            this.dialogFormVisibleEdit = false;
            this.findPage();
            return
          }
          this.$message.error(res.data.msg);
        }).catch((error) => {
          if (error == "Error: Request failed with status code 403") {
            this.$message.error("无操作权限");
          }
        });
      },
      //添加
      handleAdd() {
        axios.post("/admin/permission/add", this.formData).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '恭喜你，添加成功',
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.findPage();
          }
        }).catch((error) => {
          if (error == "Error: Request failed with status code 403") {
            this.$message.error("无操作权限");
          }
        });
      },

      findSearchPage() {
        this.pagination.currentPage = 1;
        this.findPage();
      },
      //分页查询
      findPage() {
        const params = {
          currentPage: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          queryString: this.pagination.queryString
        };
        axios.get("/users", { params }).then((res) => {
          if (res.data) {
            this.dataList = res.data.records;
            this.pagination.total = res.data.total;
          }
        }).catch((error) => {
          if (error == "Error: Request failed with status code 403") {
            this.$message.error("无操作权限");
          }
        });
      },
      // 重置表单
      resetForm() {
        this.formData = {};
        this.subjects = [];
        this.tableData = {};
      },
      // 弹出添加窗口
      handleCreate() {
        this.resetForm();
        this.dialogFormVisible = true;
      },
      // 弹出编辑窗口
      handleUpdate(row) {
        this.resetForm();
        this.dialogFormVisibleEdit = true;
        this.formData = row;
      },
      //切换页码
      handleCurrentChange(currentPage) {
        this.pagination.currentPage = currentPage;
        this.findPage();
      },
      handleReset(row) {
        this.$confirm('此操作将重置密码为 123456, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.put("/users/" + row.id + "/reset/").then((res) => {
            if (res.data) {
              this.$message.success("重置成功");
              this.findPage();
            }
          }).catch((error) => {
            if (error == "Error: Request failed with status code 403") {
              this.$message.error("无操作权限");
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置'
          });
        });

      },
      handleDelete(row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.delete("/users/" + row.id).then((res) => {
            if (res.data) {
              this.$message.success(res.data);
              this.findPage();
            }
          }).catch((error) => {
            if (error == "Error: Request failed with status code 403") {
              this.$message.error("无操作权限");
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      formatDateTime(date) {
        if (!date) return '';
        const d = new Date(date);
        const pad = num => String(num).padStart(2, '0');
        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      },

      async showRentalHistory(row) {
        this.currentUser = row;
        this.rentalHistoryVisible = true;
        this.historyQuery.currentPage = 1;
        this.historyQuery.userId = row.id;
        await this.loadRentalHistory();
      },

      async loadRentalHistory() {
        this.historyLoading = true;
        try {
          const params = {
            pageNo: this.historyQuery.currentPage,
            pageSize: this.historyQuery.pageSize,
            userId: this.historyQuery.userId
          };
          const response = await axios.get("/rentals/page", { params });
          if (response.data) {
            this.rentalHistory = response.data.records;
            this.historyTotal = response.data.total;
          }
        } catch (error) {
          if (error.response && error.response.status === 403) {
            this.$message.error("无操作权限");
          } else {
            this.$message.error("获取租号记录失败");
          }
        } finally {
          this.historyLoading = false;
        }
      },

      handleHistoryPageChange(page) {
        this.historyQuery.currentPage = page;
        this.loadRentalHistory();
      },
      getRoleName(role) {
        switch (role) {
          case '1':
            return '管理员';
          case '2':
            return '用户';
          case '3':
            return '普通会员';
          case '4':
            return '高级会员';
          default:
            return '用户';
        }
      }
    }
  });
</script>

</html>